<template>
  <div class="document-upload-container">
    <!-- 上传按钮 -->
    <div v-if="!disabled && fileList.length < maxCount" class="upload-button-area">
      <el-upload
        ref="upload"
        :action="uploadUrl"
        :headers="uploadHeaders"
        :before-upload="beforeUpload"
        :on-progress="onProgress"
        :on-success="onSuccess"
        :on-error="onError"
        :show-file-list="false"
        :accept="acceptTypes"
        :disabled="fileList.length >= maxCount"
      >
        <el-button 
          type="primary" 
          style="float: left;"
          icon="el-icon-upload"
            size="small"
          :disabled="fileList.length >= maxCount"
        >
          {{ (fileList.length >= maxCount) ? `已达上限(${maxCount})` : '选择文件' }}
        </el-button>
      </el-upload>
    </div>

    <!-- 文件列表 -->
    <div class="file-list" v-if="fileList.length > 0">
      <div 
        v-for="(item, index) in fileList" 
        :key="index"
        class="file-item"
        :class="{ 'uploading': item.uploading }"
      >
        <div class="file-info">
          <div class="file-icon">
            <i :class="getFileIcon(item.type || item.name)"></i>
          </div>
          <div class="file-details">
            <div class="file-name" :title="item.name">
              <div style="display: inline-block;width: 500px">   <span class="file-name"> {{ item.name }} </span></div>
              <span class="file-size">大小：{{ formatFileSize(item.size) }}</span> &nbsp;&nbsp;&nbsp;&nbsp;
              <span v-if="item.uploading" class="upload-status">
                上传中 {{ item.progress || 0 }}%
              </span>
           
            
            </div>
         
          </div>
        </div>
        
        <!-- 操作按钮 -->
        <div class="file-actions">
          <el-button 
            v-if="!item.uploading && item.url" 
            type="text" 
            icon="el-icon-download"
            @click="downloadFile(item)"
          >
            下载
          </el-button>
          <el-button 
            v-if="!disabled"
            type="text" 
            icon="el-icon-delete"
            @click="removeFile(index)"
            :disabled="item.uploading"
          >
            删除
          </el-button>
        </div>

        <!-- 上传进度条 -->
        <div v-if="item.uploading" class="progress-bar">
          <el-progress 
            :percentage="item.progress || 0"
            :show-text="false"
            :stroke-width="2"
          ></el-progress>
        </div>
      </div>
    </div>

    <!-- 配置说明 -->
    <div class="upload-tips" v-if="showTips && !disabled">
      <p>支持 {{ acceptTypes || '所有格式' }} 文件，单个文件不超过 {{ maxSize }}MB，最多上传 {{ maxCount }} 个文件</p>
    </div>
  </div>
</template>

<script>
import request from '@/utils/request'
import { getToken } from '@/utils/auth'

export default {
  name: 'DocumentUpload',
  props: {
    // v-model 绑定的文件数组或JSON字符串
    value: {
      type: [Array, String],
      default: () => []
    },
    // 最大上传数量
    maxCount: {
      type: Number,
      default: 20
    },
    // 最大文件大小(MB)
    maxSize: {
      type: Number,
      default: 100
    },
    // 接受的文件类型
    acceptTypes: {
      type: String,
      default: ''
    },
    // 是否显示提示信息
    showTips: {
      type: Boolean,
      default: true
    },
    // 是否禁用上传功能（只显示预览）
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      fileList: [],
      uploadUrl: 'http://125.39.77.18:9021/mall-admin/fileUpload/upload',
      uploadingCount: 0 // 正在上传的文件数量
    }
  },
  computed: {
    uploadHeaders() {
      return {
        'Authorization': 'Bearer ' + getToken()
      }
    }
  },
  watch: {
    value: {
      handler(newVal) {
        // 如果是字符串，尝试解析为数组
        let parsedValue = []
        if (typeof newVal === 'string') {
          try {
            parsedValue = newVal ? JSON.parse(newVal) : []
          } catch (error) {
            console.warn('DocumentUpload: 无法解析value字符串为JSON数组:', newVal, error)
            parsedValue = []
          }
        } else if (Array.isArray(newVal)) {
          parsedValue = newVal
        }

        this.fileList = parsedValue.map(item => ({
          ...item,
          uploading: false,
          progress: 100
        }))
      },
      immediate: true,
      deep: true
    },
    uploadingCount(newVal) {
      // 当有文件正在上传时，给容器添加特殊class
      const container = this.$el
      if (newVal > 0) {
        container.classList.add('files-uploading')
      } else {
        container.classList.remove('files-uploading')
      }
    }
  },
  methods: {
    // 上传前校验
    beforeUpload(file) {
      // 检查文件类型
      if (this.acceptTypes) {
        const isValidType = this.checkFileType(file)
        if (!isValidType) {
          this.$message.error(`只能上传 ${this.acceptTypes} 格式的文件!`)
          return false
        }
      }

      // 检查文件大小
      const isValidSize = file.size / 1024 / 1024 < this.maxSize
      if (!isValidSize) {
        this.$message.error(`上传文件大小不能超过 ${this.maxSize}MB!`)
        return false
      }

      // 检查数量限制
      if (this.fileList.length >= this.maxCount) {
        this.$message.error(`最多只能上传 ${this.maxCount} 个文件!`)
        return false
      }

      // 添加到文件列表，显示上传状态
      const tempItem = {
        name: file.name,
        size: file.size,
        type: file.type,
        url: '',
        uploading: true,
        progress: 0,
        tempFile: true
      }
      this.fileList.push(tempItem)
      this.uploadingCount++

      return true
    },

    // 上传进度
    onProgress(event, file) {
      const targetIndex = this.fileList.findIndex(item => item.tempFile && item.name === file.name)
      if (targetIndex !== -1) {
        this.fileList[targetIndex].progress = Math.round(event.percent)
        this.$forceUpdate()
      }
    },

    // 上传成功
    onSuccess(response, file) {
      const targetIndex = this.fileList.findIndex(item => item.tempFile && item.name === file.name)
      if (targetIndex !== -1) {
        // 更新文件信息
        this.fileList[targetIndex] = {
          name: response.data.name,
          size: response.data.fileSize,
          type: response.data.type,
          url: response.data.url,
          uploading: false,
          progress: 100,
          tempFile: false
        }
        
        this.uploadingCount--
        this.emitChange()
        this.$message.success('上传成功!')
      }
    },

    // 上传失败
    onError(error, file) {
      const targetIndex = this.fileList.findIndex(item => item.tempFile && item.name === file.name)
      if (targetIndex !== -1) {
        // 移除失败的文件
        this.fileList.splice(targetIndex, 1)
        this.uploadingCount--
      }
      this.$message.error('上传失败!')
    },

    // 移除文件
    removeFile(index) {
      const item = this.fileList[index]
      if (item.uploading) {
        this.uploadingCount--
      }
      this.fileList.splice(index, 1)
      this.emitChange()
    },

    // 下载文件
    downloadFile(item) {
      if (!item.url) {
        this.$message.warning('文件链接不存在')
        return
      }
      
      // 创建隐藏的下载链接
      const link = document.createElement('a')
      link.href = item.url
      link.download = item.name
      link.style.display = 'none'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    },

    // 检查文件类型
    checkFileType(file) {
      if (!this.acceptTypes) return true
      
      const acceptedTypes = this.acceptTypes.split(',').map(type => type.trim().toLowerCase())
      const fileName = file.name.toLowerCase()
      const fileType = file.type.toLowerCase()
      
      return acceptedTypes.some(type => {
        if (type.startsWith('.')) {
          return fileName.endsWith(type)
        }
        return fileType.includes(type)
      })
    },

    // 获取文件图标
    getFileIcon(fileType) {
      const type = (fileType || '').toLowerCase()
      
      if (type.includes('image') || /\.(jpg|jpeg|png|gif|bmp|svg)$/i.test(type)) {
        return 'el-icon-picture'
      } else if (type.includes('pdf') || type.endsWith('.pdf')) {
        return 'el-icon-document'
      } else if (type.includes('word') || /\.(doc|docx)$/i.test(type)) {
        return 'el-icon-document'
      } else if (type.includes('excel') || /\.(xls|xlsx)$/i.test(type)) {
        return 'el-icon-s-grid'
      } else if (type.includes('powerpoint') || /\.(ppt|pptx)$/i.test(type)) {
        return 'el-icon-data-line'
      } else if (type.includes('zip') || type.includes('rar') || /\.(zip|rar|7z)$/i.test(type)) {
        return 'el-icon-folder-opened'
      } else if (type.includes('video') || /\.(mp4|avi|mov|wmv|flv)$/i.test(type)) {
        return 'el-icon-video-camera'
      } else if (type.includes('audio') || /\.(mp3|wav|flac|aac)$/i.test(type)) {
        return 'el-icon-headset'
      } else {
        return 'el-icon-document'
      }
    },

    // 格式化文件大小
    formatFileSize(bytes) {
      if (!bytes) return '0 B'
      
      const k = 1024
      const sizes = ['B', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    },

    // 触发v-model更新
    emitChange() {
      const result = this.fileList
        .filter(item => !item.uploading && !item.tempFile)
        .map(item => ({
          name: item.name,
          size: item.size,
          type: item.type,
          url: item.url
        }))
      
      // 根据原始value类型决定输出格式
      let emitValue;
      if (typeof this.value === 'string') {
        emitValue = JSON.stringify(result);
      } else {
        emitValue = result;
      }
      
      this.$emit('input', emitValue);
      // 添加change事件支持
      this.$emit('change', emitValue, result);
    }
  }
}
</script>

<style scoped>
.document-upload-container {
  width: 100%;
}

.upload-button-area {
  margin-bottom: 0;
}

.file-list {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
}

.file-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 15px;
  border-bottom: 1px solid #ebeef5;
  transition: background-color 0.3s;
  position: relative;
  min-height: 48px;
}

.file-item:last-child {
  border-bottom: none;
}

.file-item:hover {
  background-color: #f5f7fa;
}

.file-item.uploading {
  background-color: #ecf5ff;
}

.file-info {
  display: flex;
  align-items: center;
  flex: 1;
  min-width: 0;
}

.file-icon {
  margin-right: 12px;
  font-size: 20px;
  color: #409eff;
  flex-shrink: 0;
}

.file-details {
  flex: 1;
  min-width: 0;
  text-align: left;
}

.file-name {
  font-size: 14px;
  color: #303133;
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  text-align: left;
}

.file-meta {
  display: flex;
  align-items: center;
  gap: 15px;
  font-size: 12px;
  color: #909399;
}

.upload-status.success {
  color: #67c23a;
}

.file-actions {
  display: flex;
  align-items: center;
  gap: 5px;
  flex-shrink: 0;
  margin-left: 15px;
}

.progress-bar {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 2px;
}

.upload-tips {
  margin-top: 0;
  color: #999;
  font-size: 12px;
}

.upload-tips p {
  margin: 0;
}

/* 全局class，用于检测是否有文件正在上传 */
.files-uploading {
  /* 可以添加一些样式来表示正在上传状态 */
}
</style>